package com.aliengen.thingple.driverapp.data.local;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Delete;
import com.aliengen.thingple.driverapp.network.api.exception.FieldNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@Table(name = "PlanItem")
public class PlanItemModel extends Model implements Serializable {
    @Column(name = "planitem_id",index = true,unique = true)
    public int planitem_id;

    @Column(name = "plangroup_id")
    public PlanGroupModel plan_group;

    @Column(name = "plan_id", index = true)
    public int plan_id;

    @Column(name = "plan_reference")
    public String plan_reference;

    @Column(name = "date")
    public String date;

    @Column(name = "amount")
    public int amount;

    @Column(name = "carrier")
    public String carrier;

    @Column(name = "notes")
    public String notes;

    @Column(name = "truck")
    public TruckModel truck;

    @Column(name = "customer")
    public CustomerModel customer;

    @Column(name = "product")
    public ProductModel product;

    @Column(name = "facility_code")
    public int facility;

    @Column(name = "facility_name")
    public String facility_name;

    public PlanItemModel() {
        super();
    }

    public PlanItemModel(JSONObject json) throws FieldNotFoundException {
        super();
        if (!(json.has("planitem_id") && json.has("planitem_id"))) {
            throw new FieldNotFoundException("Missing fields!");
        }

        try {
            this.planitem_id = json.getInt("planitem_id");
            this.plan_id = json.getInt("plan_id");
            this.plan_reference = json.getString("plan_reference");
            this.date = json.getString("date");

            this.amount = json.getInt("amount");
            this.carrier = json.getString("carrier");
            this.notes = json.getString("notes");
            JSONObject facility = json.getJSONObject("area");
            this.facility = facility.getInt("area_id");
            this.facility_name = facility.getString("area_name");

            this.truck = TruckModel.getOrSet(json.getJSONObject("truck"));
            this.customer = CustomerModel.getOrSet(json.getJSONObject("customer"));
            this.product = ProductModel.getOrSet(json.getJSONObject("product"));

            this.plan_group = PlanGroupModel.getOrSet(this.plan_id, this.plan_reference, this.truck.truck_id, this.date, this.customer);
        } catch(JSONException e)
        {
            throw new FieldNotFoundException(e);
        }
    }

    public static void flush()
    {
        new Delete().from(PlanItemModel.class).execute();
    }
}
